const base64 = require('../../utils/uploadImg/base64.js');

const {
  get,
  post
} = require('../../request/index')
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
const app = getApp()
let API_BASE_URL = app.globalData.baseURL.baseURL
Page({

  data: {
    loginShow: false,
    showOneButtonDialog: false,
    oneButton: [{
      text: '确定'
    }],
    loginuser: "登录",
    error: '',
    formData: {

    },
    rules: [{
        name: 'username',
        rules: {
          required: true,
          message: '账号是必填项'
        },
      },
      {
        name: 'password',
        rules: {
          required: true,
          message: '密码是必填项'
        },
      },
      {
        name: 'code',
        rules: {
          required: true,
          message: '验证码是必填项'
        },
      }
    ],
    imgser: null,
    uuid: null
  },
  onLoad() {
    this.getCode();
  },
  onUnload() {
    this.setData({
      loginShow: false

    })
  },
  getCode() {
    get('/code', {}).then(res => {
      this.setData({
        imgser: "data:image/gif;base64," + res.img,
        uuid: res.uuid
      })
    })
  },
  tapOneDialogButton(e) {
    this.setData({
      showOneButtonDialog: false
    })
  },



  formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },



  submitForm() {
    let that = this
    this.selectComponent('#form').validate((valid, errors) => {
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })

        }
      } else {
        let {
          uuid
        } = this.data
        const {
          username,
          password,
          code

        } = this.data.formData
        this.setData({
          loginShow: true,
          loginuser: "登录中..."
        })
        console.log(username, password, code, uuid);
        post('/auth/login', {
          username,
          password,
          code,
          uuid
        }).then(res => {
          if (res.code == 200) {
            wx.setStorageSync('token', JSON.stringify(res.data.access_token));
            wx.showToast({
              title: '登录成功',
              duration: 3000,
              icon: 'success',
              mask: true
            })
            wx.switchTab({
              url: '/pages/grid/grid'
            })

          } else {
            Notify({
              color: '#ad0000',
              background: '#ffe1e1',
              message:res.msg
            });
            that.setData({
              loginShow: false,
              loginuser: "登录"
            })
          }
        })
    

      }
    })

  }



})